package com.uglive.cg.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
import com.blankj.utilcode.util.ToastUtils;
import com.uglive.cg.R;
import com.uglive.cg.bean.Goods;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements MainContract.View {
    private MainContract.Presenter mPresenter;
    private ProgressDialog mProgressDialog;
    private BottomSheetDialog loginDialog;
    private AwesomeValidation mValidata;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.spSpace)
    Spinner spSpace;

    @BindView(R.id.numberInput)
    EditText numberInput;

    @BindView(R.id.barcordText)
    TextView barcordText;

    @BindView(R.id.goodsNameTv)
    TextView goodsNameTv;

    @BindView(R.id.kusTv)
    TextView kusTv;

    @BindView(R.id.message)
    TextView message;


    private static class MyHandler extends Handler {
        private WeakReference<MainActivity> ref;

        public MyHandler(WeakReference<MainActivity> ref) {
            this.ref = ref;
        }

    }

    MyHandler myHandler = new MyHandler(new WeakReference<>(this));


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        addValidate();
        initLoginDialog();
        mProgressDialog = new ProgressDialog(this);
        mPresenter = new MainPresenter(this);
        toolbar.setOnMenuItemClickListener(item -> {
            mPresenter.clearLoginInfo();
            showLoinAlert();
            return true;
        });
        mPresenter.start();
    }

    private void initLoginDialog() {
        loginDialog = new BottomSheetDialog(this);
        loginDialog.setCancelable(false);
        loginDialog.setCanceledOnTouchOutside(false);
        View view = getLayoutInflater().inflate(R.layout.layout_login, null);
        loginDialog.setContentView(view);
        Button submit = view.findViewById(R.id.login);
        TextInputLayout til = view.findViewById(R.id.phoneInputLayout);
        TextInputEditText input = view.findViewById(R.id.phoneInput);
        input.setOnClickListener(v -> histSoftInput(v));
        AwesomeValidation awe = new AwesomeValidation(ValidationStyle.TEXT_INPUT_LAYOUT);
        awe.addValidation(til, "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$", "手机号格式不对");
        submit.setOnClickListener(v -> {
            if (awe.validate()) {
                mPresenter.login(input.getText().toString());
            }
        });
        Button clear = view.findViewById(R.id.clearPhoneNumber);
        clear.setOnClickListener(v -> input.setText(""));

    }

    //添加表单验证
    private void addValidate() {
        mValidata = new AwesomeValidation(ValidationStyle.BASIC);
        mValidata.addValidation(this, R.id.barcordText, str -> !TextUtils.isEmpty(str), R.string.validate_error_barcode);
        mValidata.addValidation(this, R.id.numberInput, str -> {
            if (TextUtils.isEmpty(str)) {
                return false;
            }
            if (Integer.parseInt(str) <= 0) {
                return false;
            }
            return true;
        }, R.string.validate_error_number);
        mValidata.addValidation(
                this, R.id.spSpace,
                vh -> {
                    String item = (String) ((Spinner) vh.getView()).getSelectedItem();
                    if (TextUtils.isEmpty(item)) {
                        ToastUtils.showShort("未获取到仓库信息");
                        mPresenter.getCkList();
                        return false;
                    }
                    if (item.equals(getResources().getString(R.string.space_tooltip))) {
                        return false;
                    }
                    return true;
                },
                vh -> {
                    TextView tv = (TextView) ((Spinner) vh.getView()).getSelectedView();
                    if (null != tv) tv.setTextColor(Color.RED);
                },
                vh -> {
                    TextView tv = (TextView) ((Spinner) vh.getView()).getSelectedView();
                    if (null != tv) tv.setTextColor(Color.BLACK);
                },
                R.string.error_space_tooltip
        );
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //按扫描键获取二维码
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_F11) {
                String barCode = mPresenter.getBarCode();
                if (!TextUtils.isEmpty(barCode)) {
                    barcordText.setText(barCode);
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.close();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @OnClick(R.id.rkBtn)
    void rkSubmit() {
        if (mValidata.validate()) {
            goodsNameTv.setText(null);
            kusTv.setText(null);
            mPresenter.ruku(numberInput.getText().toString(), barcordText.getText().toString(), (String) spSpace.getSelectedItem());
        }
    }

    @OnClick(R.id.ckBtn)
    void ckSubmit() {
        if (mValidata.validate()) {
            goodsNameTv.setText(null);
            kusTv.setText(null);
            mPresenter.chuku(numberInput.getText().toString(), barcordText.getText().toString(), (String) spSpace.getSelectedItem());
        }
    }

    @Override
    public void showProcess(String msg) {
        mProgressDialog.setMessage(msg);
        mProgressDialog.show();
    }

    @Override
    public void dismissProcess() {
        mProgressDialog.dismiss();
    }

    @Override
    public void setUserInfo(String phoneNumber) {
        toolbar.setSubtitle(phoneNumber);
    }

    @Override
    public void showLoinAlert() {
        loginDialog.show();
    }

    @Override
    public void dismissLoginAlert() {
        loginDialog.dismiss();
    }

    @Override
    public void showGoodsInfo(Goods goods) {
        goodsNameTv.setText(goods.getGoodsName());
        kusTv.setText(goods.getGoodsSum());
    }

    @Override
    public void showMessage(String message) {
        this.message.setText(message);
        this.message.setVisibility(View.VISIBLE);
        myHandler.postDelayed(() -> this.message.setVisibility(View.GONE), 3000);
    }

    @Override
    public void setCkData(List<String> ckList) {
        ArrayList<String> list = new ArrayList<>(ckList);
        list.add(0,getString(R.string.space_tooltip));
        spSpace.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list));
    }

    private void histSoftInput(View v){
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

}
